package com.supermarket.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.supermarket.api.bean.order.OrderRes;
import com.supermarket.api.bean.order.pay.AliPayReq;
import com.supermarket.api.config.AliPayConfig;
import com.supermarket.api.service.OrderService;
import com.supermarket.api.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 支付服务层
 * @author 李其伟
 * @date 2023/12/15
 */
@Slf4j
@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private OrderService orderService;

    @Override
    public String aliPay(AliPayReq aliPayReq) {
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent(buildBizContent(aliPayReq.getOrderSn()));

        AlipayTradeAppPayResponse response = null;
        try {
            response = alipayClient.sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(response.getBody());
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        return response.getBody();
    }

    /**
     * 构建支付宝支付数据
     * @param orderSn
     * @return
     */
    private String buildBizContent(String orderSn){

        OrderRes orderRes = orderService.detail(orderSn);

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderRes.getOrderSn());
        bizContent.put("total_amount", orderRes.getTotalAmount());
        bizContent.put("subject", orderRes.getOrderItemEntityList().get(0).getTitle());
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");
//bizContent.put("time_expire", "2022-08-01 22:00:00");

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);


        return bizContent.toString();
    }
}

























